﻿using Himp.Erp.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace Himp.Erp
{
    public class MatlInvRepository : EfCoreRepository<ErpDbContext, MatlInv, Guid>, IMatlInvRepository
    {
        public MatlInvRepository(
            IDbContextProvider<ErpDbContext> dbContextProvider)
            : base(dbContextProvider)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task<IQueryable<MatlInv>> GetInvDetlListAsync()
        {
            var dbSet = await GetDbSetAsync();
            var result = dbSet.Where(d => d.CurFlag && d.InboundDetlId != null)
                .Include(d => d.MatlWhse).Include(d => d.MatlInfo).Include(d => d.InboundDetl);

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task<List<MatlInv>> GetInvSumListAsync(int pi, int ps)
        {
            List<MatlInv> matlInvs = new List<MatlInv>();
            var dbSet = await GetDbSetAsync();
            var groupResult = dbSet.Where(d => d.CurFlag && d.InboundDetlId != null)
                .Include(d => d.MatlWhse).Include(d => d.MatlInfo).Include(d => d.InboundDetl)
                .OrderBy(o => o.Bchno)
                .GroupBy(g => g.MatlInfoId);

            foreach (var item in groupResult)
            {
                MatlInv matlInv = new MatlInv();
                matlInv.MatlInfo = item.First().MatlInfo;
                matlInv.MatlWhse = item.First().MatlWhse;
                matlInv.FinlCnt = item.Sum(i => i.FinlCnt);
                matlInvs.Add(matlInv);
            }

            return matlInvs;
        }
    }
}
